<template>
  <div class="address-book">
    <div class="scale-1px-bottom">
      <van-search
        v-model="searchValue"
        placeholder="请输入客户名称/手机号"
        :show-action="false"
        background="#fff"
        @input="inputChang"
      >
        <i class="iconfont icon-sousuolan_sousuo" slot="left-icon"></i>
      </van-search>
    </div>
    <index-bar
      id="Bscroll"
      :shortcutList="shortcutList"
      :singers="customerList"
      :isTrigger="isLoading"
      ref="indexBar"
    >
      <div slot="upper">
        <ul>
          <router-link
            tag="li"
            class="cell van-hairline--bottom"
            v-for="item in funsList"
            :key="item.value"
            :to="item.path"
          >
            <span class="icon-box">
              <svg class="icon-svg" aria-hidden="true">
                <use :xlink:href="`#icon-${item.icon}`" />
              </svg>
              <MessageTips slot="extra" :news="item.num" />
            </span>
            <span class="title">{{ item.name }}</span>
          </router-link>
        </ul>
        <ul>
          <li class="group-title">{{ belongType ? '我的渠道' : '我的企业' }}</li>
          <li class="cell business" @click="JumpBusiness">
            <span class="icon-box">
              <svg class="icon-svg" aria-hidden="true">
                <use xlink:href="#icon-jingjigongsi" />
              </svg>
            </span>
            <span class="title" :style="{color: business.nameColor }">{{ business.name }}</span>
            <span
              class="tips"
              v-if="business.label"
              :style="{color: business.labelColor }"
            >{{ business.label }}</span>
            <i
              v-if="business.icon"
              :class="`iconfont ${business.icon}`"
              @click.stop="tipsHandle(business)"
            ></i>
          </li>
        </ul>
        <div class="loading" v-show="!isLoading && !isLogin">
          <van-loading />
        </div>
        <div class="no-data" style="margin-top: 26%;" v-if="!customerList.length && isLoading">
          <img src="@/assets/img/article/empty_article@2x.png" alt="无数据" />
          <p>暂无内容</p>
        </div>
      </div>
      <div slot-scope="props">
        <h2 class="list-group-title">{{ props.title }}</h2>
        <ul>
          <li
            v-for="item in props.items"
            class="list-group-item van-hairline--bottom"
            :key="item.clientId"
            @click="clickJump(false, item)"
          >
            <img v-lazy="item.avatarUrl" class="avatar" @click.stop="clickJump(true, item)" />
            <span class="name">{{ item.clientRemarkName }}</span>
          </li>
          <li
            v-if="props.current < props.pages"
            class="next"
            @click="getNextPage(props.title, props.current)"
          >查看更多</li>
        </ul>
      </div>
    </index-bar>
    <div class="search-view" v-if="searchValue">
      <ul v-if="searchList.length || !searchLoading">
        <li
          v-for="item in searchList"
          class="list-group-item van-hairline--bottom"
          :key="item.clientId"
          @click="clickJump(false, item)"
        >
          <img v-lazy="item.avatarUrl" class="avatar" @click.stop="clickJump(true, item)" />
          <span class="name">{{ item.clientRemarkName }}</span>
        </li>
      </ul>
      <div class="no-data" v-else>
        <img src="@/assets/img/article/empty_article@2x.png" alt />
        <p>暂无搜索内容</p>
      </div>
    </div>
    <div class="overlay" v-if="isLogin || isFirst">
      <div v-if="isLogin" class="login">
        <p class="text">登录后才能查看通讯录/消息</p>
        <span class="button" @click="jumpLogin">立即登录</span>
      </div>
      <div v-if="isFirst" class="first-dialog">
        <div class="header">欢迎来到客户追踪神器</div>
        <div class="content">
          <div class="item" v-for="item in funsList">
            <p class="title">
              <span class="icon" :style="{ background: item.color }"></span>
              <span>{{ item.name }}</span>
            </p>
            <p class="text" v-html="item.text"></p>
          </div>
        </div>
        <div class="close" @click="closeGuide">
          <i class="iconfont icon-xieyixiequxiao_tianjia"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Avatar from '@/components/Avatar'
import MessageTips from '@/components/MessageTips'
import indexBar from '@/components/indexBar'
import { mapGetters } from 'vuex'
import dynamicsService from 'SERVICE/dynamicsService'
import { debounce, isEmpty } from 'lodash'
import userService from 'SERVICE/userService'
// import singers from './testData'
import customService from '@/services/customService'

const funsList = [
  {
    name: '动态',
    color: '#F7B500',
    text: '你发的每篇文章系统都会告诉你谁看了<br/>TA对什么感兴趣<br/>精准锁定每一个意向客户',
    isTip: true,
    value: 'unreadDynamicCount',
    path: '/dynamics/activityTrack',
    num: 0,
    icon: 'dongtai'
  },
  { name: '分组', color: '#57CC29', text: '你可以对每一个客户进行批量分组管理<br/>清晰归类 便捷高效', isTip: false, value: 'group', path: '/custom/group', num: 0, icon: 'fenzu' },
  {
    name: '消息',
    color: '#007AE6',
    text: '推送客户实时消息<br/>支持在线发送楼盘和商品详情信息<br/>与客户保持畅聊',
    isTip: true,
    value: 'unreadMessageCount',
    path: '/dynamics/message/messageList',
    num: 0,
    icon: 'xiaoxi'
  }
]

let size = 20

export default {
  data() {
    return {
      funsList,
      isTrigger: false,
      isLoading: false,
      isLogin: false,
      isFirst: false,
      searchLoading: false,
      flag: true,
      searchValue: '',
      customerList: [],
      shortcutList: [],
      searchList: [],
      business: {},
      belongType: 0
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    if (!(this.userInfo && this.userInfo.token)) {
      this.isLogin = true
    } else {
      this.getBusinessInfo()
      this.getDataCenterInfo()
      this.getAllCustomer()
    }
  },
  methods: {
    async getBusinessInfo() {
      // let isFirst = window.localStorage.getItem('addressBookFirst')
      // if (!isFirst) {
      //   this.$store.commit('TABBAR', { show: false })
      //   this.isFirst = true
      //   window.localStorage.setItem('addressBookFirst', true)
      // }
      let organizationAuditVO = {}
      let business = { name: '加入经纪公司', nameColor: '#9BA4B4', label: '请选择', labelColor: '#9BA4B4', icon: 'icon-wode-erjizhe' }

      // belongType字段区分是否是项目方，项目方不显示经纪公司状态，显示渠道信息
      if (this.userInfo.belongType && this.userInfo.belongType === 2) {
        this.belongType = this.userInfo.belongType
        let uuid = localStorage.getItem('uuid') || ''
        const organizationAuditVO = await userService.getAddressIfChannel(uuid)
        if (!organizationAuditVO.type) {
          business = { key: 'channel', name: '加入渠道', nameColor: '#9BA4B4', label: '请选择', labelColor: '#9BA4B4', icon: 'icon-wode-erjizhe'  }
        } else {
          business = { key: 'channel', id: organizationAuditVO.channelId, name: organizationAuditVO.channelName, nameColor: '#13284D', icon: 'icon-shouye_tishi', click: true, isJump: true }
        }
      } else {
        // 经纪公司状态 0-审核中 1-已加入公司 2-审核失败 3-未加入公司 4- 公司删除经纪人 5-邀请加入公司 6-审核已失效
        organizationAuditVO = await userService.getAddressOrganizationAudit()
        switch (`${organizationAuditVO.auditType}`) {
          case '0':
            business = { id: organizationAuditVO.organizationId, name: organizationAuditVO.organizationName, nameColor: '#13284D', label: '审核中', labelColor: '#007AE6', isJump: true }
            break
          case '1':
            business = { id: organizationAuditVO.organizationId, name: organizationAuditVO.organizationName, nameColor: '#13284D', icon: 'icon-shouye_tishi', click: true, isJump: true }
            break
          case '2':
            business = { id: organizationAuditVO.organizationId, name: organizationAuditVO.organizationName, nameColor: '#13284D', label: '审核失败', labelColor: '#EA4D2E' }
            break
        }
      }
      this.business = business
    },
    JumpBusiness() {
      if (this.business.isJump) return false
      let path = '/user/edit/userBrokerCompany'
      if (this.business && !this.business.key) {
        path += `?id=${this.business.id || ''}`
      } else {
        path += `?module=channel&id=${this.business.id || ''}`
      }
      this.$router.push(path)
    },
    getDataCenterInfo() {
      dynamicsService
        .getDynamicsCollect()
        .then(res => {
          this.funsList.forEach(item => {
            if (item.isTip) {
              item.num = res[item.value]
            }
          })
          // 缓存首页数据
          window.sessionStorage.setItem('dataCenterInfo', JSON.stringify(res))
        })
        .catch(() => {})
    },
    async getAllCustomer() {
      let res = await customService.getAllCustomerList({ total: size, real: true })
      this.shortcutList = res.map(group => group.initial)
      this.customerList = res
      this.isLoading = true
    },
    async getNextPage(initial, current) {
      let res = await customService.getMoreCustomerList({ initial, size: 20, real: true, current: current + 1 })
      this.customerList.some(group => {
        if (group.initial === initial) {
          group.page.current = res.current
          group.page.records = group.page.records.concat(res.records)
          return true
        }
      })
      this.$nextTick(() => {
        this.$refs.indexBar._calculateHeight()
      })
    },
    clickJump(bool, item) {
      if (bool) {
        this.$router.push(`/custom/${item.clientId}`)
      } else {
        this.$router.push(`/custom/message/message?clientId=${item.clientId}`)
      }
    },
    jumpLogin() {
      let uuid = window.localStorage.getItem('uuid')
      let enterpriseId = window.localStorage.getItem('enterpriseId')
      this.$router.push(`/wx/login?uuid=${uuid}&enterpriseId=${enterpriseId}&toPath=/custom/addressBook`)
    },
    closeGuide() {
      this.isFirst = false
      // this.$store.commit('TABBAR', { show: true })
    },
    inputChang: debounce(function() {
      this.searchList = []
      this.searchLoading = false
      this.searchCustom()
    }, 500),
    async searchCustom() {
      if (!this.searchValue) return false
      let res = await customService.getAllCustomerList({ total: size, real: true, searchName: this.searchValue })
      let searchList = []
      res.forEach(group => {
        group.page.records.forEach(item => {
          searchList.push(item)
        })
      })
      this.searchList = searchList
      this.searchLoading = true
    },
    tipsHandle(item) {
      let str = this.belongType ? '已加入企业，离开企业请联系企业将您移除' : '已加入经纪公司，离开经纪公司请联系公司将您移除'
      if (item.click) {
        this.$toast(str)
      }
    }
  },
  components: {
    Avatar,
    indexBar,
    MessageTips
  }
}
</script>

<style lang="less" scoped>
.van-hairline--bottom::after {
  border-bottom-width: 0.02667rem;
  left: -25%;
}

#Bscroll {
  height: calc(100% - 56px);
}

.van-search {
  padding: 10px 16px;
  /deep/ .van-cell {
    background: #f2f6f7;
    padding: 6px 8px;
    > div {
      color: #9ca5b5;
      height: 24px;
    }
  }
}

.address-book {
  position: relative;
  background: #f7f9fa;

  .cell {
    padding: 8px 16px;
    display: flex;
    font-size: 16px;
    align-items: center;
    background: #fff;
    .icon-box {
      width: 36px;
      height: 36px;
      position: relative;
      .icon-svg {
        width: 36px;
        height: 36px;
        // vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
      }
      /deep/ .news {
        top: -6px;
        right: -6px;
        transform: scale(0.8);
      }
    }
    .title {
      flex: 1;
      margin-left: 16px;
      line-height: 36px;
    }
    .tips {
      font-size: 14px;
    }
    i {
      color: #969ea8;
    }
  }

  .group-title {
    height: 32px;
    line-height: 32px;
    padding-left: 16px;
    font-size: 12px;
    color: #405170;
    background: #f7f9fa;
  }

  .business {
    padding-right: 30px;
  }

  .loading {
    text-align: center;
    display: flex;
    justify-content: center;
    height: 200px;
    align-items: center;
  }
  .list-group-title {
    height: 32px;
    line-height: 32px;
    padding-left: 16px;
    font-size: 12px;
    color: #405170;
    background: #f7f9fa;
  }
  .list-group-item {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    .avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
    }
    .item-info {
      padding-left: 16px;
    }
    .name {
      margin-left: 20px;
      line-height: 24px;
      color: #13284d;
      font-size: 14px;
    }
    .tips {
      line-height: 16px;
      color: #9ba4b4;
      font-size: 12px;
    }
  }
  .next {
    font-size: 14px;
    text-align: center;
    padding: 12px 0;
  }
  .search-view {
    width: 100%;
    height: calc(100% - 56px);
    position: fixed;
    top: 56px;
    z-index: 100;
    background: #fff;
  }
  .no-data {
    font-size: 12px;
    text-align: center;
    margin-top: 200px;
    color: #999;
    img {
      width: 88px;
      height: 88px;
    }
  }
  .overlay {
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.65);
    z-index: 100;
    width: 100%;
    height: 100%;
    .login {
      position: absolute;
      top: 35%;
      text-align: center;
      width: 100%;
      .text {
        color: #fff;
        font-size: 16px;
        line-height: 22px;
        padding-bottom: 24px;
      }
      .button {
        display: inline-block;
        height: 32px;
        width: 100px;
        background: #007ae6;
        font-size: 14px;
        line-height: 32px;
        color: #fff;
      }
    }

    .first-dialog {
      position: absolute;
      top: 15%;
      text-align: center;
      width: 310PX;
      padding: 24PX 20PX;
      left: 50%;
      background: #fff;
      border-radius: 8PX;
      transform: translateX(-50%);
      .header {
        color: #13294f;
        font-size: 20PX;
        line-height: 28PX;
        display: none;
      }
      .content {
        background: #f6f6f6;
        margin: 16PX 0;
        padding: 28PX 12PX;
        text-align: left;
        font-size: 14PX;
        color: #405170;
        border-radius: 6PX;
        .item {
          padding-top: 20PX;
          &:first-child {
            padding-top: 0PX;
          }
          .title {
            font-size: 16PX;
            height: 22PX;
            color: #13294f;
          }
          span {
            vertical-align: middle;
          }
          .icon {
            display: inline-block;
            width: 8PX;
            height: 8PX;
            border-radius: 50%;
            margin-right: 6PX;
          }
          .text {
            line-height: 20PX;
          }
        }
      }

      .close {
        position: absolute;
        bottom: -40PX;
        left: 50%;
        transform: translateX(-50%);
        color: #fff;
        i {
          font-size: 24PX;
        }
      }
    }
  }
}
</style>